package books.storage.eao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

import books.storage.exception.EntityNotFoundException;
import books.storage.util.jpa.Entity;

@LocalBean
@Stateless
public class BooksStorageEao implements IBooksStorageEao {

	@PersistenceContext
	EntityManager em;

	public BooksStorageEao() {
	}

	public BooksStorageEao(EntityManager em) {
		this.em = em;
	} // for unit test

	public void flush() {
		em.flush();
	}

	public <T extends Entity> T findOrFail(Class<T> clazz, Integer id)
			throws EntityNotFoundException {
		T e = em.find(clazz, id);
		if (e == null) {
			throw new EntityNotFoundException(clazz.getClass(), id);
		}
		return e;
	}

	public <T extends Entity> void insertEntity(T _entity) {
		if (!_entity.hasId())
			em.persist(_entity);
		if (_entity.getId() == null)
			em.flush();
	}

	public <T extends Entity> void deleteEntity(T _entity) {
		if (_entity.hasId())
			em.remove(_entity);
		em.flush();
	}

	public <T extends Entity> void updateEntity(T _entity) {
		if (_entity.hasId())
			em.merge(_entity);
	}

	public <T extends Entity> List<T> getAllEntities(Class<T> resultClass) {
		CriteriaQuery<T> criteria = em.getCriteriaBuilder().createQuery(
				resultClass);
		return em.createQuery(criteria).getResultList();
	}

}